package main

import (
    "net/http"
    "io/ioutil"
    "encoding/json"
    "net"
    "strings"
)

type PostData struct {

    Task_id string    `json:"task_id"`
    Post ResponseData `json:"return"`
}

type GetData struct {

    Code        int         `json:"code"`
    Message     string      `json:"message"`
    Data        []*FileData `json:"data"`
    Task_id     string      `json:"task_id"`
    Conf_names  []*string   `json:"conf_names"`
    Device_name string      `json:"device_name"`
}

func getMac() string {

    var MAC string
    interfaces, err := net.Interfaces()
    if err != nil {
        mainlog.Println("get mac error.", err)
    } else {
        for _, inter := range interfaces {
            if inter.Name == "eth0" {
                mac := inter.HardwareAddr //获取本机MAC地址
                MAC = strings.ToUpper(mac.String())
            }
        }
    }
    mainlog.Println("MAC = ", MAC)
    return MAC
}

func startGet() {
    
    var ret PostData

    /*测试mac=D6:D9:75:F2:C2:C9*/
    url := g_config.getCmdApi + "?cacheClear=1&mac=" + getMac()
    mainlog.Println("getCmdApi:", url)
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        mainlog.Println("make request failed.", err)
        return
    }
    client := http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        mainlog.Println("make request failed.", err)
        return
    }
    defer resp.Body.Close()
    
    respBytes, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        mainlog.Println(err)
        return
    }

    var data GetData
    err = json.Unmarshal(respBytes, &data)
    if err != nil {
        mainlog.Println(err)
        return
    }

    if data.Code == -1 {

        mainlog.Println("get cmd failed.")
        mainlog.Println("error message.", data.Message)
        return
    }

    mainlog.Println("get cmd success.")
    mainlog.Println("task_id:", data.Task_id)

    ret.Post.Detail = make([]*CMDResult, 0)

    for _,v := range data.Data {
        cmdres := &CMDResult{}
        cmdres.Name = v.Name
        cmdres.Success = "1"
        cmdres.Error = ""

        if err := dealWithFileData(v); err != nil {
            cmdres.Success = "0"
            cmdres.Error = err.Error()
        }

        ret.Post.Detail = append(ret.Post.Detail, cmdres)
    }

    ret.Task_id = data.Task_id
    ret.Post.Success = "1"
    ret.Post.Error = ""
    mainlog.Println("post result to api")
    postRet(&ret)
}
